package com.hopechart.micro.config;

import com.hopechart.micro.common.exception.BusinessException;
import com.hopechart.micro.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.support.GenericConversionService;
import org.springframework.util.Assert;
import org.springframework.web.bind.support.ConfigurableWebBindingInitializer;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;

import javax.annotation.PostConstruct;
import java.text.ParseException;
import java.util.Date;

/**
 * <p>
 *     <br/>日期转换器配置
 * </p>
 * @author daijiang@hopechart.com
 * @date 2017-10-30 08:59:54
 * @copyright 杭州鸿泉数字设备有限公司
 * @version V1.0.0
 */
@Configuration
public class DateConverterConfig {

    @Autowired
    private RequestMappingHandlerAdapter handlerAdapter;

    @PostConstruct
    public void addConversionConfig() {
        ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer)handlerAdapter.getWebBindingInitializer();
        if (initializer.getConversionService() != null) {
            GenericConversionService genericConversionService = (GenericConversionService)initializer.getConversionService();
            genericConversionService.addConverter(new DateConverter());
        }
    }

    public class DateConverter implements Converter<String, Date> {

        @Override
        public Date convert(String dateString) {
            Assert.hasText(dateString, "日期字符串为空");
            Date date;
            try {
                date = DateUtil.parseDate(dateString, DateUtil.parsePatterns);
            } catch (ParseException e) {
                throw new BusinessException("日期字符串" + dateString + "转换异常", e);
            }

            return date;
        }
    }
}
